﻿/*
 * 由SharpDevelop创建。
 * 用户： aaa
 * 日期: 2017/2/26
 * 时间: 16:46
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace d1
{
	class Program
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			
			// TODO: Implement Functionality Here
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
		
		Socket serverSocket = null;
Thread clientThread = null;
Socket clientSocket = null;
Thread thread = null;
IPAddress ips = null;
PEndPoint ipep = null;
void ServerStart()
{
  ips = Dns.GetHostAddresses(Dns.GetHostName())[0];
  //创建IPEndPoint实例  
  ipep = new IPEndPoint(ips, 9050);
  //创建一个套接字  
  serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  //将所创建的套接字与IPEndPoint绑定  
  serverSocket.Bind(ipep);
  //设置套接字为收听模式  
  serverSocket.Listen(20);
  while (listenalive)
  {
    try
    {
      //在套接字上接收接入的连接  
      clientSocket = serverSocket.Accept();
      clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
      clientThread.Start(clientSocket);
    }
    catch (Exception ex)
    {
      WriteErrorLog(ex.Message);
      serverSocket.Close();
      serverSocket = null;
    }
  }
}
static void ReceiveData(object obj)
{
  bool keepalive = true;
  Socket s = obj as Socket;
  Byte[] buffer = new Byte[1024];
  //根据收听到的客户端套接字向客户端发送信息  
  IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
  Console.WriteLine("客户端ip:" + clientep.Address + " 端口:" + clientep.Port);
  string welcome = "连接服务器成功";
  buffer = System.Text.Encoding.Unicode.GetBytes(welcome);
  //向客户端发送“连接服务器成功”消息
  s.Send(buffer, buffer.Length, SocketFlags.None);
  buffer = new Byte[1024];
  int bufLen = 0;
  string content = string.Empty;
  while (true)
  {
    //在套接字上接收客户端发送的信息  
    bufLen = 0;
    try
    {
      bufLen = s.Receive(buffer);
      if (bufLen == 0)
      {
        break;
      }
      content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen);
    }
    catch (Exception ex)
    {
      break; ;
    }
  }
  Send(s, content);
  s = null;
  buffer = null;
  clientep = null;
  Thread.CurrentThread.Abort();
}
	}
}